/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.aptech.mBean;

import com.aptech.entities.CartBean;
import com.aptech.entities.TblElevation;
import com.aptech.entities.TblOrder;
import com.aptech.entities.TblOrderDetail;
import com.aptech.entities.TblOrderDetailPK;
import com.aptech.entities.TblUser;
import com.aptech.mBean.util.JsfUtil;
import com.aptech.mBean.util.PaginationHelper;
import com.aptech.sBean.TblElevationFacade;
import com.aptech.sBean.TblOrderDetailFacade;
import com.aptech.sBean.TblOrderFacade;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.event.ActionEvent;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpSession;
import org.primefaces.context.RequestContext;

/**
 *
 * @author Winner
 */
@ManagedBean(name = "orderDetailsController")
@SessionScoped
public class OrderDetailController implements Serializable {

    @EJB
    private TblOrderFacade tblOrderFacade;
    @EJB
    private TblElevationFacade tblElevationFacade;
    @EJB
    private TblOrderDetailFacade tblOrderDetailFacade;
    private TblOrderDetail current;
    private DataModel items = null;
    private PaginationHelper pagination;
    private TblElevation tblElevation;
    private int elIDOrder;
    private int oddQuantity;
    private CartBean cartBean;
    private TblOrder tblOrder;

    public TblOrderDetail getCurrent() {
        return current;
    }

    public void setCurrent(TblOrderDetail current) {
        this.current = current;
    }

    public TblOrder getTblOrder() {
        if (tblOrder == null) {
            tblOrder = new TblOrder();
        }
        return tblOrder;
    }

    public void setTblOrder(TblOrder tblOrder) {
        this.tblOrder = tblOrder;
    }

    public TblElevation getTblElevation() {
        return tblElevation;
    }

    public void setTblElevation(TblElevation tblElevation) {
        this.tblElevation = tblElevation;
    }

    public int getElIDOrder() {
        return elIDOrder;
    }

    public void setElIDOrder(int elIDOrder) {
        this.elIDOrder = elIDOrder;
    }

    public void updateTblElevation(TblElevation tblElevation) {
        this.tblElevation = tblElevation;
    }

    public void chooseTblElevationToOrder(TblElevation tblElevation) {
        System.out.println("Choose elevation" + tblElevation.getElName());
        this.tblElevation = tblElevation;
    }

    public int getOddQuantity() {
        return oddQuantity;
    }

    public void setOddQuantity(int oddQuantity) {
        this.oddQuantity = oddQuantity;
    }

    public CartBean getCartBean() {
        return cartBean;
    }

    public void setCartBean(CartBean cartBean) {
        this.cartBean = cartBean;
    }

    /**
     * Creates a new instance of OrderDetailController
     */
    public OrderDetailController() {
    }

    public String addToCart(TblElevation e) {
        System.out.println(e.getElID());
        String outcome = "CartManager";
        List<TblElevation> list = tblElevationFacade.getTblElevationToOrder(e.getElID());
        if (list == null) {
            return outcome;
        }
        e = list.get(0);
        if (cartBean == null) {
            cartBean = new CartBean();
        }
        cartBean.addItem(e);

        return outcome;
    }

    public String deleteItemCart(TblOrderDetail od) {
        String outcome = "CustomerOrder";
        if (cartBean == null) {
            return outcome;
        }
        cartBean.delete(od);
        return outcome;
    }

    public String clearCart() {
        String outcome = "CustomerOrder";
        if (cartBean != null) {
            cartBean.clear();
        }
        return outcome;
    }
    //Chưa check CLient đã đăng nhập hay chưa, mới set tạm thôi

    public String checkOut() {
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        TblUser user = (TblUser) session.getAttribute("UserSession");
        if (user == null) {
            return null;
        }
        tblOrder.setMnID(null);
        tblOrder.setUsID(user);
        tblOrder.setOdTotal(cartBean.calculateTotal());
        tblOrder.setOdCreated(new Date());
        tblOrder.setOdStatus(0);
        tblOrder.setTblOrderDetailList(new ArrayList<TblOrderDetail>());
        tblOrderFacade.create(tblOrder);

        List<TblOrderDetail> listTblOrderDetail = cartBean.getCart();
        for (int i = 0; i < listTblOrderDetail.size(); i++) {
            listTblOrderDetail.get(i).setTblOrder(tblOrder);
            TblOrderDetail od = new TblOrderDetail();
            od.setTblOrder(tblOrder);
            od.setOddPrice(cartBean.calculatePrice(listTblOrderDetail.get(i).getTblElevation()));
            od.setOddQuantity(listTblOrderDetail.get(i).getOddQuantity());
            od.setTblElevation(listTblOrderDetail.get(i).getTblElevation());
            TblOrderDetailPK tblOrderDetailPK = new TblOrderDetailPK();
            tblOrderDetailPK.setElID(listTblOrderDetail.get(i).getTblElevation().getElID());
            tblOrderDetailPK.setOdID(tblOrder.getOdID());
            od.setTblOrderDetailPK(tblOrderDetailPK);
            tblOrderDetailFacade.create(od);
        }
        clearCart();
        return "CustomerOrder";
    }

    public TblOrderDetail getSelected() {
        if (current == null) {
            current = new TblOrderDetail();
            current.setTblOrderDetailPK(new com.aptech.entities.TblOrderDetailPK());
        }
        return current;
    }

    public TblOrderDetailFacade getFacade() {
        return tblOrderDetailFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {
                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(tblOrderDetailFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(tblOrderDetailFacade.findAll(), true);
    }

    @FacesConverter(forClass = TblOrderDetail.class)
    public static class OrderDetailsControllerConverter implements Converter {

        private static final String SEPARATOR = "#";
        private static final String SEPARATOR_ESCAPED = "\\#";

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            OrderDetailController controller = (OrderDetailController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "orderDetailsController");
            return controller.tblOrderDetailFacade.find(getKey(value));
        }

        com.aptech.entities.TblOrderDetailPK getKey(String value) {
            com.aptech.entities.TblOrderDetailPK key;
            String values[] = value.split(SEPARATOR_ESCAPED);
            key = new com.aptech.entities.TblOrderDetailPK();
            key.setOdID(Integer.parseInt(values[0]));
            key.setElID(Integer.parseInt(values[1]));
            return key;
        }

        String getStringKey(com.aptech.entities.TblOrderDetailPK value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value.getOdID());
            sb.append(SEPARATOR);
            sb.append(value.getElID());
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof TblOrderDetail) {
                TblOrderDetail o = (TblOrderDetail) object;
                return getStringKey(o.getTblOrderDetailPK());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + TblOrderDetail.class.getName());
            }
        }
    }

    public void checkLogin(ActionEvent actionEvent) {
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        TblUser user = (TblUser) session.getAttribute("UserSession");
        if (user == null) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, "Err :", "You are not the login"));
        }

    }
}
